<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * oauth2.0
 */
class OAuth2 extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->helper('output');
		$this->load->model(array('oauth2/oauth_model', 'oauth2/OAuth', 'app/app_model'));

		$this->load->config('errno');
		$this->_errno = $this->config->item('errno');
	}

	/**
	 * 展示授权页面
	 */
	public function Authorize() {
		$appid  = $this->input->get_post('appid', TRUE);
		$redirect_uri = $this->input->get_post('redirect_uri', TRUE);
		$response_type = $this->input->get_post('response_type', TRUE);//code
		$scope = $this->input->get_post('scope', TRUE);// 应用授权作用域
		$action = $this->input->get_post('action', TRUE);

		$params = array(
				'appid' => $appid,
				'redirect_uri' => $redirect_uri,
				'response_type' => $response_type,
				'scope' => $scope,
			);

		if (!in_array($scope, array('snsapi_base', 'snsapi_userinfo'))) {
			error_output(ERROR_INVALID_SCOPE, $this->_errno);
		}

		if ($scope == 'snsapi_userinfo') {
			if('authorize' != $action) {
				return $this->load->view('oauth2/oauth2_connect', $params);
			}
		}

		$user_id = $this->oauth_model->getLoginUserID();
		$is_authorized = $user_id ? true : false;
		$this->OAuth->finishClientAuthorization($is_authorized, $params, $user_id);
	}

	/**
	 * 换取 access token
	 */
	public function AccessToken() {
		$ret = $this->OAuth->grantAccessToken();
		output($ret);
	}

	/**
	 * 刷新 access token
	 */
	public function RefreshToken() {
		$ret = $this->OAuth->grantAccessToken();
		output($ret);
	}

}
